package com.showtao.front.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.HandlerMapping;

import com.showtao.common.constant.ApplicationConstant;

@Controller
public class ResourceController implements ServletContextAware {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ResourceController.class);

	private ServletContext sc;
	private AntPathMatcher matcher = new AntPathMatcher();

	@RequestMapping(value = ApplicationConstant.UPLOAD_TEMP_URI
			+ "/{fileName}.{ext}", method = RequestMethod.GET)
	public void viewTemp(@PathVariable("fileName") String fileName,
			@PathVariable("ext") String ext, Model model,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		String mime = sc.getMimeType("mock." + ext);
		response.setContentType(mime != null ? mime : "image/jpeg");
		File tempDir = new File(
				sc.getRealPath(ApplicationConstant.UPLOAD_TEMP_FOLDER));
		File tempFile = FileUtils.getFile(tempDir, fileName + "." + ext);
		ServletOutputStream os = response.getOutputStream();
		FileUtils.copyFile(tempFile, os);
	}

	@RequestMapping(value = ApplicationConstant.FILE_URI + "/**", method = RequestMethod.GET)
	public void view(Model model, HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws IOException {
		try {
			// Don't repeat a pattern
			String pattern = (String) request
					.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
			String fileName = matcher.extractPathWithinPattern(pattern,
					request.getServletPath());
			LOGGER.info("path="+request.getServletPath());
			LOGGER.info("file="+fileName);
			if (StringUtils.isEmpty(fileName)) {
				throw new RuntimeException("no such file can be founded.");
			}
			String[] fns = fileName.split("\\.");
			if (fns == null || fns.length == 0) {
				throw new RuntimeException("filename=" + fileName
						+ " is invalid.");
			}
			String ext = fns[fns.length - 1];
			String mime = sc.getMimeType("mock." + ext);
			response.setContentType(mime != null ? mime : "image/jpeg");
			File file = new File(
					sc.getRealPath(ApplicationConstant.FILE_FOLDER) + "/"
							+ fileName);
			ServletOutputStream os = response.getOutputStream();
			FileUtils.copyFile(file, os);
		} catch (IOException e) {
			response.sendRedirect(sc.getContextPath()
					+ "/assets/img/noimage.jpg");
		} catch (RuntimeException re) {
			response.sendRedirect(sc.getContextPath()
					+ "/assets/img/noimage.jpg");
		}
	}

	@Override
	public void setServletContext(ServletContext sc) {
		this.sc = sc;
	}
}
